<template>
  <div class="comment-review">
    <div class="page-header">
      <h2>评论审核</h2>
      <div class="filter-actions">
        <el-select v-model="filterType" placeholder="审核状态" style="width: 120px; margin-right: 10px;">
          <el-option label="全部" value="" />
          <el-option label="待审核" value="pending" />
          <el-option label="已通过" value="approved" />
          <el-option label="已拒绝" value="rejected" />
        </el-select>
        <el-select v-model="filterSource" placeholder="来源" style="width: 120px; margin-right: 10px;">
          <el-option label="全部" value="" />
          <el-option label="影片评论" value="movie" />
          <el-option label="弹幕" value="danmaku" />
        </el-select>
        <el-button @click="handleSearch" type="primary">查询</el-button>
        <el-button @click="handleBatchApprove" type="success">批量通过</el-button>
        <el-button @click="handleBatchReject" type="danger">批量拒绝</el-button>
      </div>
    </div>
    
    <el-card>
      <template #header>
        <span>待审核内容</span>
      </template>
      
      <el-table
        :data="reviewList"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="commentContent" label="内容" min-width="300">
          <template #default="scope">
            <div class="content-preview">
              <p class="content-text">{{ scope.row.commentContent }}</p>
              <div class="content-meta">
                <span class="movie">影片: {{ scope.row.movieTitle }}</span>
                <span class="user">用户: {{ scope.row.username }}</span>
                <span class="time">时间: {{ scope.row.createdAt }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="success" @click="handleApprove(scope.row)">通过</el-button>
            <el-button size="small" type="danger" @click="handleReject(scope.row)">拒绝</el-button>
            <el-button size="small" @click="handleViewDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 评论详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="评论详情"
      width="600px"
    >
      <div class="comment-detail">
        <div class="detail-item">
          <label>用户:</label>
          <span>{{ currentComment?.username }}</span>
        </div>
        <div class="detail-item">
          <label>影片:</label>
          <span>{{ currentComment?.movieTitle }}</span>
        </div>
        <div class="detail-item">
          <label>时间:</label>
          <span>{{ currentComment?.createdAt }}</span>
        </div>
        <div class="detail-item">
          <label>内容:</label>
          <div class="content-box">{{ currentComment?.commentContent }}</div>
        </div>
        <div class="detail-item" v-if="currentComment?.reviewComment">
          <label>审核意见:</label>
          <span>{{ currentComment.reviewComment }}</span>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="success" @click="handleApprove(currentComment)">通过</el-button>
        <el-button type="danger" @click="handleReject(currentComment)">拒绝</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reviewService } from '../../services/reviewService'
import { useAuthStore } from '../../stores/auth'

const loading = ref(false)
const filterType = ref('')
const filterSource = ref('')
const detailDialogVisible = ref(false)
const selectedComments = ref([])
const currentComment = ref(null)

const reviewList = ref([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 加载待审核评论列表
const loadReviews = async () => {
  loading.value = true
  try {
    const response = await reviewService.getPendingReviews({
      page: pagination.current - 1,
      size: pagination.size,
      type: filterType.value,
      source: filterSource.value
    })
    reviewList.value = response.data.content || []
    pagination.total = response.data.totalElements || 0
  } catch (error) {
    console.error('加载评论列表失败:', error)
    ElMessage.error('加载评论列表失败')
  } finally {
    loading.value = false
  }
}

const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return textMap[status] || '未知'
}

const handleSelectionChange = (selection) => {
  console.log('选中的评论:', selection)
  selectedComments.value = selection
}

const handleApprove = async (comment) => {
  try {
    await ElMessageBox.confirm(
      '确定要通过这条评论吗？',
      '审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    console.log('comment', comment)
    // 获取当前登录用户信息
    const authStore = useAuthStore()
    const currentUser = authStore.userInfo
    
    const reviewRequest = {
      id: comment.id,
      commentId: comment.commentId,
      commentContent: comment.commentContent,
      commentRating: comment.commentRating,
      movieId: comment.movieId,
      movieTitle: comment.movieTitle,
      userId: comment.userId,
      username: comment.username,
      reviewerId: currentUser?.userId ,
      reviewerName: currentUser?.username ,
      status: 'approved',
      reviewComment: '审核通过'
    }
    await reviewService.reviewComment(reviewRequest)
    ElMessage.success('审核通过')
    loadReviews()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核评论失败:', error)
      ElMessage.error('审核评论失败')
    }
  }
}

const handleReject = async (comment) => {
  try {
    await ElMessageBox.confirm(
      '确定要拒绝这条评论吗？',
      '审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 获取当前登录用户信息
    const authStore = useAuthStore()
    const currentUser = authStore.userInfo
    
    const reviewRequest = {
      id: comment.id,
      commentId: comment.commentId,
      commentContent: comment.commentContent,
      commentRating: comment.commentRating,
      movieId: comment.movieId,
      movieTitle: comment.movieTitle,
      userId: comment.userId,
      username: comment.username,
      reviewerId: currentUser?.userId ,
      reviewerName: currentUser?.username ,
      status: 'rejected',
      reviewComment: '审核拒绝'
    }
    await reviewService.reviewComment(reviewRequest)
    ElMessage.success('已拒绝')
    loadReviews()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('拒绝评论失败:', error)
      ElMessage.error('拒绝评论失败')
    }
  }
}

const handleViewDetail = async (comment) => {
  try {
    const response = await reviewService.getReviewDetail(comment.id)
    currentComment.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取评论详情失败:', error)
    ElMessage.error('获取评论详情失败')
  }
}

const handleBatchApprove = async () => {
  if (selectedComments.value.length === 0) {
    ElMessage.warning('请选择要审核的评论')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要通过选中的 ${selectedComments.value.length} 条评论吗？`,
      '批量审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    console.log('选中的评论对象:', selectedComments.value)
    // 获取当前登录用户信息
    const authStore = useAuthStore()
    const currentUser = authStore.userInfo
    
    const reviewRequests = selectedComments.value.map(comment => ({
      id: comment.id,
      commentId: comment.commentId,
      commentContent: comment.commentContent,
      commentRating: comment.commentRating,
      movieId: comment.movieId,
      movieTitle: comment.movieTitle,
      userId: comment.userId,
      username: comment.username,
      reviewerId: currentUser?.userId ,
      reviewerName: currentUser?.username ,
      status: 'approved',
      reviewComment: '批量审核通过'
    }))
    console.log('批量审核请求:', reviewRequests)
    
    await reviewService.batchReview(reviewRequests)
    ElMessage.success('批量审核通过')
    selectedComments.value = []
    loadReviews()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量审核失败:', error)
      ElMessage.error('批量审核失败')
    }
  }
}

const handleBatchReject = async () => {
  if (selectedComments.value.length === 0) {
    ElMessage.warning('请选择要审核的评论')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要拒绝选中的 ${selectedComments.value.length} 条评论吗？`,
      '批量审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 获取当前登录用户信息
    const authStore = useAuthStore()
    const currentUser = authStore.userInfo
    
    const reviewRequests = selectedComments.value.map(comment => ({
      id: comment.id,
      commentId: comment.commentId,
      commentContent: comment.commentContent,
      commentRating: comment.commentRating,
      movieId: comment.movieId,
      movieTitle: comment.movieTitle,
      userId: comment.userId,
      username: comment.username,
      reviewerId: currentUser?.userId ,
      reviewerName: currentUser?.username ,
      status: 'rejected',
      reviewComment: '批量审核拒绝'
    }))
    
    await reviewService.batchReview(reviewRequests)
    ElMessage.success('批量审核拒绝')
    selectedComments.value = []
    loadReviews()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量拒绝失败:', error)
      ElMessage.error('批量拒绝失败')
    }
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadReviews()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadReviews()
}

// 查询按钮处理函数
const handleSearch = () => {
  pagination.current = 1
  loadReviews()
}

onMounted(() => {
  loadReviews()
})
</script>

<style scoped>
.comment-review {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.filter-actions {
  display: flex;
  align-items: center;
}

.content-preview {
  padding: 8px 0;
}

.content-text {
  margin: 0 0 8px 0;
  line-height: 1.5;
}

.content-meta {
  font-size: 12px;
  color: #666;
}

.content-meta span {
  margin-right: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.comment-detail .detail-item {
  margin-bottom: 15px;
}

.detail-item label {
  font-weight: bold;
  margin-right: 10px;
  color: #333;
}

.content-box {
  margin-top: 5px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  line-height: 1.5;
}
</style>